package com.common.util.update;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.common.util.R;
import com.common.util.utils.AppUtils;
import com.common.util.utils.LogUtils;
import com.common.util.utils.ToastUtils;

import java.io.File;

/**
 * Created by liangjianbin on 17/6/20.
 */

public class AppUpdateDialog extends Dialog {
    /**
     * 应用下载存储路径
     */
    private final String APK_PATH = Constant.filePath;

    private Context mContext;
    private TextView mTvTitle;
    private TextView mTvContent;

    private TextView mTvLeftBtn;
    private TextView mTvRightBtn;

    private View mHorizonTalLayout;
    private View mLlUpdateTip;
    private CustomProgressBar mProgressBar;

    public AppUpdateDialog(@NonNull Context context) {
        super(context);
        this.mContext = context;
        initView();
        initAttributes();
    }

    public AppUpdateDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, R.style.MyDialog);
        this.mContext = context;
        initView();
    }

    private void initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_update_dialog, null);
        setContentView(view);

        mTvTitle = (TextView) view.findViewById(R.id.tv_title);
        mTvContent = (TextView) view.findViewById(R.id.tv_content);
        mTvLeftBtn = (TextView) view.findViewById(R.id.tv_left);
        mTvRightBtn = (TextView) view.findViewById(R.id.tv_right);
        mHorizonTalLayout = view.findViewById(R.id.horizontal_dialog);
        mLlUpdateTip = view.findViewById(R.id.ll_update_tip);
        mProgressBar = view.findViewById(R.id.progressBar);
    }

    private void initAttributes() {
        Window window = this.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setWindowAnimations(R.style.exist_dialog_animstyle);
        window.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.dialog_corner_bg));
        /*
         * 将对话框的大小按屏幕大小的百分比设置
         */
        WindowManager m = window.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用x`
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.85); // 宽度设置为屏幕的0.65
        window.setAttributes(p);

        setCanceledOnTouchOutside(false);
        setCancelable(false);
    }

    public void setTitle(int resId) {
        mTvTitle.setText(mContext.getResources().getString(resId));
    }

    public void setTtitle(String title) {
        mTvTitle.setText(title);
    }

    public void setContent(int resId) {
        mTvContent.setText(mContext.getResources().getString(resId));
    }

    public void setContent(String title) {
        mTvContent.setText(title);
    }

    public void setHorizonTalLayoutVisibility(int visibility) {
        mHorizonTalLayout.setVisibility(visibility);
    }


    public void setLeftBtnText(String text) {
        mTvLeftBtn.setText(text);
    }

    public void setRightBtnText(String text) {
        mTvRightBtn.setText(text);
    }


    public void setLeftBtnListener(View.OnClickListener onClickListener) {
        mTvLeftBtn.setOnClickListener(onClickListener);
    }

    public void setRightBtnListener(View.OnClickListener onClickListener) {
        mTvRightBtn.setOnClickListener(onClickListener);
    }

    public AppUpdateDialog setCancelVisible(int visibile) {
        mTvLeftBtn.setVisibility(visibile);
        return this;
    }

    public void setCancel(String title) {
        if (mHorizonTalLayout.getVisibility() == View.VISIBLE) {
            setLeftBtnText(title);
        }
    }

    public void setConfirm(String title) {
        if (mHorizonTalLayout.getVisibility() == View.VISIBLE) {
            setRightBtnText(title);
        }
    }

    public void setCancelListener(View.OnClickListener clickListener) {
        if (mHorizonTalLayout.getVisibility() == View.VISIBLE) {
            setLeftBtnListener(clickListener);
        }
    }

    public void setConfirmListener(View.OnClickListener clickListener) {
        if (mHorizonTalLayout.getVisibility() == View.VISIBLE) {
            setRightBtnListener(clickListener);
        }
    }

    public void startDownload(String apkUrl) {
        if (UpdateManager.getInstance().checkApkFileExists()) {
            installApk();
            dismiss();
            return;
        }

        mLlUpdateTip.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.VISIBLE);
        UpdateManager.getInstance().startDownloads(apkUrl, APK_PATH, new UpdateDownloadListener() {
            @Override
            public void onStarted() {
                LogUtils.e("tag", "onStarted()");

            }

            @Override
            public void onProgressChanged(int progress, String downloadUrl) {
                LogUtils.e("tag", progress+"");
                mProgressBar.setProgress(progress);
            }

            @Override
            public void onFinished(float completeSize, String downloadUrl) {
                LogUtils.e("tag", "onFinished()");
                dismiss();
                installApk();
            }

            @Override
            public void onFailure() {
                LogUtils.e("tag", "onFailure()");
                dismiss();
            }
        });
    }


    /**
     * 通过隐式意图调用系统安装程序安装APK
     * 进入apk安装程序
     * @return
     */
    public void installApk() {
        try {
            LogUtils.e("tag", "installApk()");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            File apkFile = new File(APK_PATH);
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= 24) {
                //Uri apkUri = FileProvider.getUriForFile(mContext, AppUtils.getPackageName() + ".fileProvider", apkFile);
                Uri apkUri = FileProvider.getUriForFile(mContext, "com.common.utils.fileProvider", apkFile);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
//                intent.setDataAndType(Uri.parse("file://"+apkFile.getAbsolutePath()),
//                    "application/vnd.android.package-archive");
            }
            mContext.getApplicationContext().startActivity(intent);
        } catch (Exception e) {
            LogUtils.e("tag", e.toString());
        } finally {
//            UpdateManager.getInstance().deleteLocalApkFile();
        }
    }

    /**
     * 显示升级对话框
     * @param context
     * @param dataBean
     * @param upgradeListener
     * @return
     */
    public static AppUpdateDialog showUpdateDialog(final Context context, AppVersionInfoResBeen.DataBean dataBean, final AppUpgradeListener upgradeListener) {
        if (dataBean == null) {
            dataBean = new AppVersionInfoResBeen.DataBean();
        }
        dataBean.setAdownUrl("https://github.com/gonjay/rubychina4android/blob/master/app/build/apk/app-debug-unaligned.apk?raw=true");
//        dataBean.setType("01");
        dataBean.setVerNo("1.1.0");
        dataBean.setUpdateText("1.更新内容2\n2.更新内容2");

        final String downUrl = dataBean.getAdownUrl();
        String localAppVersion = AppUtils.getVersionName();
        localAppVersion = localAppVersion == null ? "0" : localAppVersion;
        String updateFlag = dataBean.getType() == null ? "" : dataBean.getType();      // 00最新版本  02建议升级  01强制升级
        if (TextUtils.isEmpty(localAppVersion)) {
            return null;
        }
        String serverAppVersion = dataBean.getVerNo() == null ? "0" : dataBean.getVerNo();

        try {
            if (localAppVersion.compareTo(serverAppVersion) > 0) {
                return null;
            }
        } catch(Exception e){}

        final AppUpdateDialog updateDialog = new AppUpdateDialog(context);
        updateDialog.setTtitle("发现新版本");
        updateDialog.setContent(dataBean.getUpdateText());
        updateDialog.setHorizonTalLayoutVisibility(View.VISIBLE);
        updateDialog.setCancelable(true);

        updateDialog.setConfirmListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(downUrl)) {
                    upgradeListener.update(downUrl);
                } else {
                    ToastUtils.showBottom(context, "下载地址为空，请在管理平台配置");
                    updateDialog.dismiss();
                }
            }
        });
        updateDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });
        if (localAppVersion.equals(serverAppVersion) && updateFlag.equals(AppUpgradeListener.NO_NEW_APP_UPDATE)) {
            // 最新版本
        } else if (!localAppVersion.equals(serverAppVersion) && updateFlag.equals(AppUpgradeListener.SUGGEST_APP_UPDATE)) {
            // 建议更新
            setonDismissListener(updateDialog, upgradeListener, updateFlag);
            updateDialog.setCancel("以后再说");
            updateDialog.show();
        } else if (!localAppVersion.equals(serverAppVersion) && updateFlag.equals(AppUpgradeListener.FORCE_APP_UPDATE)) {
            // 强制更新
            setonDismissListener(updateDialog, upgradeListener, updateFlag);
            updateDialog.setCancelVisible(View.GONE);
            updateDialog.setConfirm("强制更新");
            updateDialog.show();
        }
        return updateDialog;
    }

    private static void setonDismissListener(final AppUpdateDialog updateDialog, final AppUpgradeListener upgradeListener, final String updateFlag) {
        updateDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (updateFlag.equals(AppUpgradeListener.SUGGEST_APP_UPDATE)) {
                    UpdateManager.getInstance().stopDownload();
                } else if (updateFlag.equals(AppUpgradeListener.FORCE_APP_UPDATE)) {
                    UpdateManager.getInstance().deleteLocalApkFile();
                    upgradeListener.exitApp();
                }
            }
        });
    }

    public interface AppUpgradeListener{
        /**
         * 升级常量相关
         */
        /**建议升级*/
        public static final String NO_NEW_APP_UPDATE = "00";
        /**建议升级*/
        public static final String SUGGEST_APP_UPDATE = "02";
        /**强制升级*/
        public static final String FORCE_APP_UPDATE = "01";

        void update(String downUrl);
        void exitApp();
    }
}
